<!-- 查询区 -->
<div id="searchContainer"></div>
<div class="row1 up_row">
    <div class="data_container">
        <!-- 按钮区 -->
        <div id="buttonsDiv">
            <button type="button" id="newPackage" class="am-btn am-btn-primary am-radius am-btn-xs">新增升级包</button>
            <button type="button" id="toBatchUpPackage" class="am-btn am-btn-secondary am-radius am-btn-xs">批量修改升级包</button>
        </div>
        <!-- 数据列表区 -->
        <div id="contentDiv" class="content_div"></div>
    </div>
</div>
<script src="/public/js/timeago/timeago.min.js"></script>
<script>
$(function() {
    // 加载查询区
    var searchBar = new SearchBar({
        containerId: "searchContainer",
        textPlaceholder: '查询条件：模块名、升级包名、升级内容、升级包文件名',
        queryList: [
            { title: "升级项目", key: "packageProjectId", url: "/select/getUpgradeProjects?key=packageProjectId", forSort: 7 },
            { title: "是否发布", key: "confirm_publish", data: { key: "confirm_publish", datas: [{ code: "1", name: "是" }, { code: "0", name: "否" }] } }
        ],
        queryFunc: function() { load(); }
    });
    searchBar.render();

    // 加载表格
    var workGrid = new WorkGrid({
        url: '/upgradePackage/query',
        searchBar: searchBar,
        checkbox: true,
        checkboxProperty: "id",
        columns: [{
                display: "APP名称",
                sort: "appname_en",
                width: "12%",
                maxlength: 10,
                view: '{{appname_en}}({{appname_cn}})'
            },
            { display: "模块", property: "module", sort: "module", width: "8%" },
            { display: "描述", property: "description", sort: "description", width: "18%" },
            { display: "创建人", property: "create_username", sort: "create_username", width: "7%" },
            {
                display: "创建时间",
                sort: "create_time",
                width: "7%",
                view: '<div class="need_to_be_rendered" role="tip" tip="{{create_time_display}}" datetime="{{create_time_display}}"></div>'
            },
            {
                display: "文件数",
                sort: "file_count",
                width: "6%",
                view: function(col) {
                    if (col.file_count === 0) {
                        return '<font color="red">0</font>';
                    }
                    return col.file_count;
                }
            },
            {
                display: "绑定项目",
                width: "7%",
                view: function(col) {
                    var _bind_projects = col.bind_projects || '';
                    var c = _bind_projects !== '' ? _bind_projects.split(',').length : 0;
                    return '<span class="am-badge ' + (c > 0 ? 'am-badge-secondary' : '') + ' am-round" role="tip" tip="' + _bind_projects + '">' + c + '</span>';
                }
            },
            {
                display: "是否发布",
                sort: "is_publish",
                width: "7%",
                view: function(col) {
                    if (col.is_publish === 1) {
                        return '<a class="am-badge am-badge-success am-round">是</a>';
                    } else {
                        return '<a class="am-badge am-round">否</a>';
                    }
                }
            }, {
                display: "版本号",
                property: "version",
                sort: "version",
                width: "6%"
            },
            {
                display: "操作",
                view: function(col) {
                    var view = '';

                    if (col.is_publish === 0) {
                        view += '<button type="button" data-id="' + col.id + '" data-action="toBindProject" class="am-btn am-btn-primary am-btn-mini am-radius">绑定项目</button>&nbsp;';
                    }

                    view += '<button type="button" data-id="' + col.id + '" data-action="uploadInfo" class="am-btn am-btn-secondary am-btn-mini am-radius">查看</button>&nbsp;';

                    var _bind_projects = col.bind_projects || '';
                    if (_bind_projects !== '' && col.is_publish === 0) {
                        view += '<button type="button" data-id="' + col.id + '" data-action="publish" class="am-btn am-btn-success am-btn-mini am-radius">发布</button>&nbsp;';
                    }

                    view += '<button type="button" data-id="' + col.id + '" data-action="remove" class="am-btn am-btn-danger am-btn-mini am-radius">删除</button>';
                    return view;
                }
            }
        ],
        loadAfterListener: function() {
            // 格式化创建时间的格式
            timeago().render(document.querySelectorAll('.need_to_be_rendered'), 'zh_CN');

            // 绑定提示
            $('[role="tip"]').mouseover(function() {
                var _this = $(this);
                _this.justToolsTip({
                    animation: "moveInTop",
                    contents: _this.attr('tip') || '',
                    gravity: 'top'
                });
            })

            // 绑定项目
            $('#contentDiv [data-action="toBindProject"]').click(function() {
                var id = $(this).attr('data-id');
                var url = "/upgradePackage/toBindProject?id=" + id + "&_=" + new Date().getTime();
                zeroModal.show({ url: url, title: '绑定项目', width: '700px', height: '400px', onClosed: function() { workGrid.load(); } });
            });

            // 查看
            $('#contentDiv [data-action="uploadInfo"]').click(function() {
                var id = $(this).attr('data-id');
                var url = "/upgradePackage/uploadInfo?id=" + id + "&_=" + new Date().getTime();
                zeroModal.show({ url: url, title: '查看升级包', width: '70%', height: '400px', onClosed: function() { workGrid.load(); } });
            });

            // 发布
            $('#contentDiv [data-action="publish"]').click(function() {
                var val = $(this).attr('data-id');
                zeroModal.confirm({
                    content: '确认发布升级包吗？',
                    contentDetail: '发布后将不能进行修改，请谨慎操作！',
                    okFn: function() {
                        $.ajax({
                            url: '/upgradePackage/publish',
                            dataType: "json",
                            type: "post",
                            data: 'id=' + val,
                            success: function(data) {
                                if (data.success) {
                                    $.toast({ text: '发布成功！', showHideTransition: 'slide', icon: 'success', position: 'top-center' });
                                } else {
                                    $.toast({ text: '发布失败！', showHideTransition: 'slide', icon: 'error', position: 'top-center' });
                                }
                                load();
                            }
                        });
                    }
                });
            });

            // 删除
            $('#contentDiv [data-action="remove"]').click(function() {
                var val = $(this).attr('data-id');
                zeroModal.confirm({
                    content: '确认删除升级包吗？',
                    okFn: function() {
                        $.ajax({
                            url: '/upgradePackage/remove',
                            dataType: "json",
                            type: "post",
                            data: 'id=' + val,
                            success: function(data) {
                                if (data.success) {
                                    $.toast({ text: '删除成功！', showHideTransition: 'slide', icon: 'success', position: 'top-center' });
                                } else {
                                    $.toast({ text: '删除失败！', showHideTransition: 'slide', icon: 'error', position: 'top-center' });
                                }
                                load();
                            }
                        });
                    }
                });
            });
        }
    });
    workGrid.render();

    // 上传
    $('#newPackage').click(function() {
        var url = "/upgradePackage/toUpload?_=" + new Date().getTime();
        var title = "上传升级包";
        zeroModal.show({ url: url, iframe: true, title: title, width: '800px', height: '70%', onClosed: function() { workGrid.load(); } });
    });

    $('#toBatchUpPackage').click(function() {
        var ids = _bs_getSelectIds('chk_contentDiv');
        if (ids == '') {
            zeroModal.error('请选择记录进行操作！');
            return;
        }
        var url = "/upgradePackage/toBatchUpPackage?ids=" + ids + "&_=" + new Date().getTime();
        zeroModal.show({ url: url, title: '批量修改升级包', width: '900px', height: '500px', onClosed: function() { workGrid.load(); } });
    });

    // 查询
    function load(params) {
        workGrid.load(1, params);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 绑定按钮区事件
    $('[btn-action="edit"]').click(function() {
        edit();
    });

    $('[btn-action="mergeDownloadPackage"').click(function() {
        var ids = _bs_getSelectIds("chk_contentDiv");
        if (ids == "") { myUtil.alert("请选择记录进行操作！"); return; }

        var upgradeProjectId = "";
        var datas = workGrid.findDatas("id", ids);
        for (var i = 0; i < datas.length; i++) {
            if (upgradeProjectId != "" && datas[i].upgrade_project_id != upgradeProjectId) {
                myUtil.alert("只能选择同一个项目的升级包进行合并下载操作！");
                return;
            }
            upgradeProjectId = datas[i].upgrade_project_id;
        }
    });

    function edit(id) {
        $.confirm({
            content: 'url:/upgradePackage/edit?id=' + (id || '') + '&_=' + new Date().getTime() + '&' + searchBar.getQueryParams(),
            title: id ? '修改升级包' : '新增升级包',
            columnClass: 'col-md-8 col-md-offset-2',
            confirm: function() {
                if (!$("#myEditForm").valid())
                    return false;

                $.ajax({
                    url: '/upgradePackage/save',
                    dataType: "json",
                    cache: false,
                    type: "post",
                    data: $('#myEditForm').serialize(),
                    success: function(data) {
                        if (data.success) {
                            myUtil.toast_success("保存成功！");
                        } else {
                            myUtil.toast_failure("保存失败！");
                        }
                        load();
                    }
                });
            }
        });
    }

    function toUpload(id) {
        var data = workGrid.findData("id", id);
        var _title = (data.original_file_path != null ? "查看" : "上传") + "升级包";
        var _url = "url:/upgradePackage/" + (data.original_file_path != null ? "uploadInfo" : "toUpload");
        var _columnClass = (data.original_file_path != null ? "col-md-10 col-md-offset-1" : "col-md-8 col-md-offset-2");
        window.jc = $.confirm({
            content: _url + '?id=' + (id || '') + '&_=' + new Date().getTime(),
            title: _title,
            columnClass: _columnClass,
            confirmButton: false,
            onClose: function() { load(); }
        });
    }
});
</script>